import React, { Fragment } from "react"
import "./index.css"
import ReactDom from "react-dom"
class Modal extends React.Component {
    constructor() {
        super()
        this.state = {
            isVisible: false,//用于标记是否点击关闭按钮
            isHandleClose: false
        }
        this.modalRoot=document.createElement("div")
        this.modalRoot.id="protal"
    }

    static getDerivedStateFromProps(nextProps, nextState) {
        if (nextState.isHandleClose) {
            return {
                isVisible: nextState.isVisible,
                isHandleClose: false//重新初始化
            }
        }
        return {
            isVisible: nextProps.visible
        }

    }
    componentDidMount(){
        document.body.appendChild(this.modalRoot)
    }
    componentWillUnmount(){
        document.body.removeChild(this.modalRoot)
    }
    handleClose = () => {
        this.setState({
            isVisible: false,
            isHandleClose: true
        })
    }
    render() {

        let { isVisible } = this.state
        let { onOk, onCancel, children, title } = this.props
    
        let defaultEl = <Fragment>
            <p>兄弟们，今晚要大杀四方！</p>
            <p>兄弟们，今晚要大杀四方！</p>
            <p>兄弟们，今晚要大杀四方！</p>
        </Fragment>
        if (!onOk || typeof onOk !== "function") {
            throw new Error("请一定要传入一个onOk函数")
        }
        if (!onCancel || typeof onCancel !== "function") {
            throw new Error("请一定要传入一个onCacel函数")
        }
        let modalEl = (
            <div className="modal">
                <div className="mask">
                    <div className="content">
                        <button className="close" onClick={this.handleClose}>×</button>
                        <div className="header">
                            {title ? title : "提示"}
                        </div>
                        <div className="body">
                            {children ? children : defaultEl}
                        </div>
                        <div className="footer">
                            <button onClick={onCancel} className="btn1">取消</button>
                            <button onClick={onOk} className="btn2">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        )
        return isVisible ?ReactDom.createPortal(modalEl,this.modalRoot) : null
    }
}
export default Modal